package com.pureut.production.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.domain.*;
import com.pureut.production.domain.dto.*;
import com.pureut.production.domain.dto.system.SysPrintTemplateDto;
import com.pureut.production.domain.vo.*;
import com.pureut.production.mapper.*;
import com.pureut.production.service.*;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.QualityFeginService;
import com.pureut.system.api.SchedulingPlanFeignService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.BackAdjustVo;
import com.pureut.system.api.vo.BackWeight;
import com.pureut.system.api.vo.QualitySchemeConfigurationVo;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: CM
 * @date: 2023/2/9  11:21
 */
@Service
public class SpunlaceOrderServiceImpl extends ServiceImpl<SpunlaceOrderMapper, SpunlaceOrder> implements SpunlaceOrderService {

    @Resource
    private SpunlaceOrderMapper spunlaceOrderMapper;

    /**
     * 工艺卡Mapper
     */
    @Resource
    private ProcessSheetMapper processSheetMapper;

    //工艺卡模板Service
    @Resource
    private ProcessCardTempleteService processCardTempleteService;

    //工艺卡Service
    @Resource
    private ProcessSheetService processSheetService;

    //工序流程Mapper
    @Resource
    private OperationProcessMapper operationProcessMapper;

    //工艺卡日志Service
    @Resource
    private ProcessCardLogService processCardLogService;

    @Resource
    private FeignService feignService;

    /**
     * 工艺卡关联设备mapper
     */
    @Resource
    private ProcessTempleteDrviceCardMapper processTempleteDrviceCardMapper;

    /**
     * 工艺卡设备Service
     */
    @Resource
    private ProcessTempleteDrviceCardService processTempleteDrviceCardService;

    /**
     * 工艺卡设备属性
     */
    @Resource
    private ProcessPropertyCardService processPropertyCardService;

    /**
     * 工艺卡设备属性mapper
     */
    @Resource
    private ProcessPropertyCardMapper processPropertyCardMapper;

    @Resource
    private QualityFeginService qualityFeginService;

    /**
     * 工艺卡日志关联设备mapper
     */
    @Resource
    private ProcessTempleteDrviceLogMapper processTempleteDrvicelogMapper;

    /**
     * 工艺卡日志设备Service
     */
    @Resource
    private ProcessTempleteDrviceLogService processTempleteDrviceLogService;

    /**
     * 工艺卡日志设备属性
     */
    @Resource
    private ProcessPropertyLogService processPropertyLogService;

    /**
     * 工艺卡日志属性mapper
     */
    @Resource
    private ProcessPropertyLogMapper processPropertyLogMapper;

    /**
     * 水刺产出Service
     */
    @Resource
    private SpunlaceOutputService spunlaceOutputService;

    /**
     * 水刺产出Mapper
     */
    @Resource
    private SpunlaceOutputMapper spunlaceOutputMapper;

    /**
     * 水刺产出明细Mapper
     */
    @Resource
    private SpunlaceOutputDetailMapper spunlaceOutputDetailMapper;

    /**
     * 车间
     */
    @Resource
    private SysShopModelingMapper shopModelingMapper;

    /**
     * 分切执行单
     */
    @Resource
    @Lazy
    private CutOrdersDocumentService cutOrdersDocumentService;

    @Resource
    private MaterialFinishedMapper materialFinishedMapper;

    /**
     * 小卷打包
     */
    @Resource
    private RollPackingMapper rollPackingMapper;

    @Resource
    DegreasDocumentService degreasDocumentService;

    /**
     * 成品称重
     */
    @Resource
    private WeighingFinishedMaterialProductMapper weighingFinishedMaterialProductMapper;

    /**
     * 排程下达
     */
    @Resource
    private SchedulingPlanFeignService schedulingPlanFeignService;

    /**
     * 投料记录mapper
     */
    @Resource
    @Lazy
    private IFeedRecordService iFeedRecordService;

    /**
     * 仓库fegin
     */
    @Resource
    StorageFegin storageFegin;

    /**
     * 停产
     *
     * @param spunlaceOrderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean ldle(SpunlaceOrderVo spunlaceOrderVo) {
        //获取停产状态
        String ldleType = spunlaceOrderVo.getLdleType();
        //查询当前指令单状态
        SpunlaceOrder spunlaceOrder = spunlaceOrderMapper.selectById(spunlaceOrderVo.getId());
        String documentStatus = spunlaceOrder.getDocumentStatus();
        if (!"1".equals(documentStatus)) {
            throw new GlobalException("只能对生产中的制令单进行停产操作");
        }
        //暂停生产此指令单，稍后恢复生产
        if ("0".equals(ldleType)) {

            //修改水刺产出单据为暂停状态
            SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, spunlaceOrder.getSpunlaceOrderNumber()));
            spunlaceOutput.setProductionStatus("2");
            spunlaceOutputService.updateById(spunlaceOutput);
            //修改当前单据状态为暂停状态
            spunlaceOrder.setDocumentStatus("2");

            BackAdjustVo backAdjustVo = new BackAdjustVo();
            backAdjustVo.setExecutionState(4);//暂停
            backAdjustVo.setExecutionDoc(spunlaceOrder.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
            AjaxResult ajaxResult = schedulingPlanFeignService.backAdjust(backAdjustVo);
            if ("500".equals(ajaxResult.get("code"))) {
                throw new GlobalException("暂停失败");
            }

            return updateById(spunlaceOrder);
        } else {
            //暂停生产此指令单，生产下一指令单

            //修改当前单据状态为挂起状态，上线下一指令单
            spunlaceOrder.setDocumentStatus("3");
            //设置挂起时间
            spunlaceOrder.setSuspensionTime(new Date());
            boolean b = updateById(spunlaceOrder);

            //修改水刺产出单据状态为挂起
            SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, spunlaceOrder.getSpunlaceOrderNumber()));
            spunlaceOutput.setProductionStatus("3");
            spunlaceOutputService.updateById(spunlaceOutput);

            BackAdjustVo backAdjustVo1 = new BackAdjustVo();
            backAdjustVo1.setExecutionState(4);//暂停
            backAdjustVo1.setExecutionDoc(spunlaceOrder.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
            AjaxResult ajaxResult = schedulingPlanFeignService.backAdjust(backAdjustVo1);
            if ("500".equals(ajaxResult.get("code"))) {
                throw new GlobalException("暂停失败");
            }

            boolean update = true;
            if (b) {
                //查询当前线别下，待上线，并且开工时间最近的指令单
                SpunlaceOrder byTime = spunlaceOrderMapper.getByTime(spunlaceOrder.getProductionLine());

                if (byTime != null) {
                    SpunlaceOrder timeSpunlaceOrder = spunlaceOrderMapper.selectById(byTime.getId());


                    if (timeSpunlaceOrder != null) {
                        //修改为生产中
                        timeSpunlaceOrder.setDocumentStatus("1");

                        String spunlaceOrderNumber = timeSpunlaceOrder.getSpunlaceOrderNumber();
                        //查询生产领料数据
                        AjaxResult ajaxResult2 = storageFegin.spunlaceNumber(spunlaceOrderNumber);
                        List<StockOutInfoDto> data = JSONArray.parseArray(JSON.toJSONString(ajaxResult2.get("data")), StockOutInfoDto.class);

                        if(data.size() != 0){
                            List<FeedRecord> resultList = new ArrayList<>();
                            for(StockOutInfoDto entity : data){
                                FeedRecord feedRecord = new FeedRecord();
                                feedRecord.setFeedOrderNumber(timeSpunlaceOrder.getSpunlaceOrderNumber());
                                feedRecord.setLineCode(timeSpunlaceOrder.getProductionLine());
                                feedRecord.setMaterialCode(entity.getMaterialCode());
                                if (timeSpunlaceOrder.getBomWeight()!=null){
                                    feedRecord.setDeliveryWeight(entity.getPlannedWeight());
                                }

                                feedRecord.setCreateBy(SecurityUtils.getUsername());
                                feedRecord.setFeedType("1");

                                MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, timeSpunlaceOrder.getMaterialCode()));

                                feedRecord.setMaterialName(materialFinished.getMaterialName());
                                feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
                                resultList.add(feedRecord);
                            }
                            iFeedRecordService.insertBatchRecord(resultList);
//                            iFeedRecordService.insertFeedRecord(feedRecord);
                        }


                        //新增实际开工时间
                        timeSpunlaceOrder.setActualStartTime(new Date());


                        //回传排程实际开工时间
                        BackAdjustVo backAdjustVo = new BackAdjustVo();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                        backAdjustVo.setActualStartTime(simpleDateFormat.format(new Date()));
                        backAdjustVo.setExecutionDoc(timeSpunlaceOrder.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
                        backAdjustVo.setExecutionState(3);//生产中

                        AjaxResult ajaxResult1 = schedulingPlanFeignService.backAdjust(backAdjustVo);
                        if ("500".equals(ajaxResult1.get("code"))) {
                            throw new GlobalException("停产失败");
                        }

                        update = updateById(timeSpunlaceOrder);

                        //查询水刺产出是否存在单据
                        SpunlaceOutput spunlaceOutput1 = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, timeSpunlaceOrder.getSpunlaceOrderNumber()));

                        if (spunlaceOutput1 == null) {

                            //生成水刺产出列表
                            SpunlaceOutputVo spunlaceOutputVo = new SpunlaceOutputVo();

                            spunlaceOutputVo.setProductionLine(timeSpunlaceOrder.getProductionLine());//生产线别
                            spunlaceOutputVo.setWorkshop(timeSpunlaceOrder.getWorkshop());
                            spunlaceOutputVo.setSpunlaceOrderNumber(timeSpunlaceOrder.getSpunlaceOrderNumber());//制令单号
                            spunlaceOutputVo.setProductionStatus("1");//生产状态  生产中
                            spunlaceOutputVo.setMaterialCode(timeSpunlaceOrder.getMaterialCode());//物料编码
                            spunlaceOutputVo.setMotherBreadth(timeSpunlaceOrder.getMotherBreadth());//母卷幅宽
                            spunlaceOutputVo.setRollingDiameter(timeSpunlaceOrder.getRollingDiameter());//卷径
                            spunlaceOutputVo.setProductionPlanNumber(timeSpunlaceOrder.getProductionPlanNumber());//生产计划单号
                            spunlaceOutputVo.setPlanWeight(timeSpunlaceOrder.getPlanWeight());//计划重量
                            spunlaceOutputVo.setThick(timeSpunlaceOrder.getThick());//厚度
                            spunlaceOutputService.add(spunlaceOutputVo);
                        } else {
                            spunlaceOutput1.setProductionStatus("1");
                            spunlaceOutputService.updateById(spunlaceOutput1);
                        }
                    }
                }
            } else {
                throw new GlobalException("停产失败");
            }
            return update;
        }
    }

    /**
     * 复产
     *
     * @param spunlaceOrderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean prolific(SpunlaceOrderVo spunlaceOrderVo) {
        //查询单据状态
        SpunlaceOrder spunlaceOrder = spunlaceOrderMapper.selectById(spunlaceOrderVo.getId());
        String documentStatus = spunlaceOrder.getDocumentStatus();

        if (!"2".equals(documentStatus) && !"3".equals(documentStatus)) {
            throw new GlobalException("只能对暂停或者挂起的制令单进行复产操作");
        }

        //如果是暂停
        if ("2".equals(documentStatus)) {
            //修改水刺产出单据状态为生产中
            SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, spunlaceOrder.getSpunlaceOrderNumber()));
            spunlaceOutput.setProductionStatus("1");
            spunlaceOutputService.updateById(spunlaceOutput);

            //把当前暂停的单据状态改为生产中
            spunlaceOrder.setDocumentStatus("1");
            spunlaceOrder.setActualStartTime(new Date());
            //回传排程实际开工时间
            BackAdjustVo backAdjustVo = new BackAdjustVo();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            backAdjustVo.setActualStartTime(simpleDateFormat.format(new Date()));
            backAdjustVo.setExecutionDoc(spunlaceOrder.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
            backAdjustVo.setExecutionState(3);//生产中

            AjaxResult ajaxResult = schedulingPlanFeignService.backAdjust(backAdjustVo);
            if ("500".equals(ajaxResult.get("code"))) {
                throw new GlobalException("恢复失败");
            }

            spunlaceOrder.setRecevoryTime(new Date());
            return updateById(spunlaceOrder);
        } else {
            //如果是挂起

            //判断当前线别是否存在生产中的指令单
            List<SpunlaceOrder> spunlaceOrders = spunlaceOrderMapper.selectList(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getDocumentStatus, 1).eq(SpunlaceOrder::getProductionLine,spunlaceOrder.getProductionLine()));
            if (spunlaceOrders.size() > 0) {
                //修改复产指令单为待上线
                spunlaceOrder.setDocumentStatus("4");
                //添加上线顺序
                spunlaceOrder.setIsRun("1");

                return updateById(spunlaceOrder);
            } else {
                //修改水刺产出单据状态为生产中
                SpunlaceOutput spunlaceOutput = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, spunlaceOrder.getSpunlaceOrderNumber()));
                spunlaceOutput.setProductionStatus("1");
                spunlaceOutputService.updateById(spunlaceOutput);

                //把当前挂起的单据状态改为生产中
                spunlaceOrder.setDocumentStatus("1");
                spunlaceOrder.setActualStartTime(new Date());
                //回传排程实际开工时间
                BackAdjustVo backAdjustVo = new BackAdjustVo();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                backAdjustVo.setActualStartTime(simpleDateFormat.format(new Date()));
                backAdjustVo.setExecutionDoc(spunlaceOrder.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
                backAdjustVo.setExecutionState(3);//生产中

                AjaxResult ajaxResult = schedulingPlanFeignService.backAdjust(backAdjustVo);
                if ("500".equals(ajaxResult.get("code"))) {
                    throw new GlobalException("恢复失败");
                }
                spunlaceOrder.setRecevoryTime(new Date());
                return updateById(spunlaceOrder);
            }
        }

    }

    /**
     * 关结
     * @param spunlaceOrderCloseVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean close(SpunlaceOrderCloseVo spunlaceOrderCloseVo) {

        //只能对暂停和挂起的指令单进行关结
        SpunlaceOrder spunlaceOrder = spunlaceOrderMapper.selectById(spunlaceOrderCloseVo.getId());
        if (!"2".equals(spunlaceOrder.getDocumentStatus()) && !"3".equals(spunlaceOrder.getDocumentStatus())) {
            throw new GlobalException("只能对暂停或者挂起的制令单进行关结");
        }
        spunlaceOrder.setDocumentStatus("9");
        spunlaceOrder.setCloseMan(SecurityUtils.getUsername());
        spunlaceOrder.setCloseTime(new Date());
        spunlaceOrder.setCloseCause(spunlaceOrderCloseVo.getCloseCause());
        boolean b = updateById(spunlaceOrder);

        SpunlaceOutput spunlaceOutput =spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, spunlaceOrder.getSpunlaceOrderNumber()));
        spunlaceOutput.setProductionStatus("5");
        spunlaceOutputMapper.updateById(spunlaceOutput);

        BackAdjustVo backAdjustVo1 = new BackAdjustVo();
        backAdjustVo1.setExecutionState(5);//关结
        backAdjustVo1.setExecutionDoc(spunlaceOrder.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
        AjaxResult ajaxResult1 = schedulingPlanFeignService.backAdjust(backAdjustVo1);
        if ("500".equals(ajaxResult1.get("code"))) {
            throw new GlobalException("关结失败");
        }

        boolean close = true;
        if (b) {

            //判断当前线别是否存在生产中的指令单
            List<SpunlaceOrder> spunlaceOrders = spunlaceOrderMapper.selectList(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getDocumentStatus, 1).eq(SpunlaceOrder::getProductionLine,spunlaceOrder.getProductionLine()));
            if (spunlaceOrders.size() == 0) {
                //查询预计开工时间最近的线别下的制令单
                //查询当前线别下，待上线，并且开工时间最近的指令单
                SpunlaceOrder byTime = spunlaceOrderMapper.getByTime(spunlaceOrder.getProductionLine());
                if (byTime !=null ){
                SpunlaceOrder timeSpunlaceOrder = spunlaceOrderMapper.selectById(byTime.getId());
                if (timeSpunlaceOrder != null) {
                    //修改为生产中
                    timeSpunlaceOrder.setDocumentStatus("1");

                    String spunlaceOrderNumber = timeSpunlaceOrder.getSpunlaceOrderNumber();
                    //查询生产领料数据
                    AjaxResult ajaxResult2 = storageFegin.spunlaceNumber(spunlaceOrderNumber);
                    List<StockOutInfoDto> data = JSONArray.parseArray(JSON.toJSONString(ajaxResult2.get("data")), StockOutInfoDto.class);

                    if(data.size() != 0){
                        List<FeedRecord> resultList = new ArrayList<>();
                        for(StockOutInfoDto entity : data){
                            FeedRecord feedRecord = new FeedRecord();
                            feedRecord.setFeedOrderNumber(timeSpunlaceOrder.getSpunlaceOrderNumber());
                            feedRecord.setLineCode(timeSpunlaceOrder.getProductionLine());
                            feedRecord.setMaterialCode(entity.getMaterialCode());
                            if (timeSpunlaceOrder.getBomWeight()!=null){
                                feedRecord.setDeliveryWeight(entity.getPlannedWeight());
                            }

                            feedRecord.setCreateBy(SecurityUtils.getUsername());
                            feedRecord.setFeedType("1");
//                            feedRecord.setMaterialName(materialFinished.getMaterialName());
//                            feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
                            resultList.add(feedRecord);
                        }
                        iFeedRecordService.insertBatchRecord(resultList);
//                            iFeedRecordService.insertFeedRecord(feedRecord);
                    }

//                    FeedRecord feedRecord = new FeedRecord();
//
//                    feedRecord.setFeedOrderNumber(timeSpunlaceOrder.getSpunlaceOrderNumber());
//                    feedRecord.setLineCode(timeSpunlaceOrder.getProductionLine());
//                    feedRecord.setMaterialCode(timeSpunlaceOrder.getMaterialCode());
//                    if (timeSpunlaceOrder.getBomWeight()!=null){
//                        feedRecord.setDeliveryWeight(Double.parseDouble(timeSpunlaceOrder.getBomWeight()));
//                    }
//
//
//                    feedRecord.setCreateBy(SecurityUtils.getUsername());
//                    feedRecord.setFeedType("1");
//
//                    MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, timeSpunlaceOrder.getMaterialCode()));
//
//                    feedRecord.setMaterialName(materialFinished.getMaterialName());
//                    feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
//
//                    iFeedRecordService.insertFeedRecord(feedRecord);


                    timeSpunlaceOrder.setActualStartTime(new Date());
                    //回传排程实际开工时间
                    BackAdjustVo backAdjustVo = new BackAdjustVo();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    backAdjustVo.setActualStartTime(simpleDateFormat.format(new Date()));
                    backAdjustVo.setExecutionDoc(timeSpunlaceOrder.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
                    backAdjustVo.setExecutionState(3);//生产中

                    AjaxResult ajaxResult = schedulingPlanFeignService.backAdjust(backAdjustVo);
                    if ("500".equals(ajaxResult.get("code"))) {
                        throw new GlobalException("关结失败");
                    }

                    close = updateById(timeSpunlaceOrder);
                    //查询水刺产出是否存在单据
                    SpunlaceOutput spunlaceOutput1 = spunlaceOutputMapper.selectOne(new QueryWrapper<SpunlaceOutput>().lambda().eq(SpunlaceOutput::getSpunlaceOrderNumber, timeSpunlaceOrder.getSpunlaceOrderNumber()));

                    if (spunlaceOutput1 == null) {
                        //水刺产出列表上线
                        SpunlaceOutputVo spunlaceOutputVo = new SpunlaceOutputVo();

                        spunlaceOutputVo.setProductionLine(timeSpunlaceOrder.getProductionLine());//生产线别
                        spunlaceOutputVo.setWorkshop(timeSpunlaceOrder.getWorkshop());
                        spunlaceOutputVo.setSpunlaceOrderNumber(timeSpunlaceOrder.getSpunlaceOrderNumber());//制令单号
                        spunlaceOutputVo.setProductionStatus("1");//生产状态  生产中
                        spunlaceOutputVo.setMaterialCode(timeSpunlaceOrder.getMaterialCode());//物料编码
                        spunlaceOutputVo.setMotherBreadth(timeSpunlaceOrder.getMotherBreadth());//母卷幅宽
                        spunlaceOutputVo.setRollingDiameter(timeSpunlaceOrder.getRollingDiameter());//卷径
                        spunlaceOutputVo.setThick(timeSpunlaceOrder.getThick());
                        spunlaceOutputVo.setProductionPlanNumber(timeSpunlaceOrder.getProductionPlanNumber());//生产计划单号
                        spunlaceOutputVo.setPlanWeight(timeSpunlaceOrder.getPlanWeight());
                        spunlaceOutputService.add(spunlaceOutputVo);

                    } else {
                        spunlaceOutput1.setProductionStatus("1");
                        spunlaceOutputService.updateById(spunlaceOutput1);
                    }
                }}
            }

            //当该计划单对应的水刺制令单全为完成或者关结时修改
            String productionPlanNumber = spunlaceOrder.getProductionPlanNumber();
            //通过计划单号，判断是否是合并单
            String[] split = productionPlanNumber.split(",");

            //定义所有水刺制令单完成或者关结的标志
            boolean flag = true;


            for (String planNumber : split) {
                //查出计划单对应的所有水刺制令单
                List<SpunlaceOrder> spunlaceOrderList = spunlaceOrderMapper.selectList(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getProductionPlanNumber, planNumber));

                for (SpunlaceOrder order : spunlaceOrderList) {
                    //如果不为已完成或者已关结修改标志为false
                    if (!"8".equals(order.getDocumentStatus()) && !"9".equals(order.getDocumentStatus())) {
                        flag = false;
                        break;
                    }
                }

                //查出计划单对应的所有分切制令单
                List<CutOrdersDocument> cutOrdersDocumentList = spunlaceOrderMapper.getFqInfo(planNumber);

                if (flag) {

                    for (CutOrdersDocument cutOrdersDocument : cutOrdersDocumentList) {
                        if (4 != cutOrdersDocument.getProductStatus() && 5 != cutOrdersDocument.getProductStatus()) {
                            flag = false;
                            break;
                        }
                    }
                }
            }


            if (flag) {
                BackWeight backWeight = new BackWeight();
                backWeight.setPlanCode(productionPlanNumber);
                //修改排程单和排程计划单状态为已完成
                schedulingPlanFeignService.updatePlanFinishStatus(backWeight);
            }

        }
        return close;
    }

    /**
     * 水刺制令单列表
     *
     * @param spunlaceOrderVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<SpunlaceOrderDto> getList(SpunlaceOrderVo spunlaceOrderVo) {
        List<SpunlaceOrderDto> spunlaceOrderList = spunlaceOrderMapper.getSpunlaceOrderList(spunlaceOrderVo);
        for (SpunlaceOrderDto spunlaceOrderDto : spunlaceOrderList) {
            List<SysDictData> statusArray = DictUtils.getDictCache("spunlace_order_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
            Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            //单位
            spunlaceOrderDto.setMaterialUnitDict(unitMap.get(spunlaceOrderDto.getMaterialUnit()));

            //单据状态
            spunlaceOrderDto.setDocumentStatusDict(spunlaceOrderDto.getDocumentStatus());
            spunlaceOrderDto.setDocumentStatus(statusMap.get(spunlaceOrderDto.getDocumentStatus()));
        }
        return spunlaceOrderList;
    }

    /**
     * 水刺生产查看
     *
     * @param id
     * @return
     */
    @Override
    public SpunlaceOrderViewDto view(Long id) {
        SpunlaceOrderViewDto spunlaceOrderViewDto = spunlaceOrderMapper.getView(id);

        //网形
        List<SysDictData> typeArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //铺网类型
        List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
        Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        spunlaceOrderViewDto.setMaterialNetDict(typeMap.get(spunlaceOrderViewDto.getMaterialNet()));
        spunlaceOrderViewDto.setMaterialNetTypeDict(netTypeMap.get(spunlaceOrderViewDto.getMaterialNetType()));
        return spunlaceOrderViewDto;
    }

    /**
     * 根据线别查出工艺卡
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PublicProcessDto processView(Long id) {
        //获取当前制令单信息
        SpunlaceOrderDto spunlaceOrder = spunlaceOrderMapper.selectSpunlace(id);
        if (!"5".equals(spunlaceOrder.getDocumentStatus())) {
            throw new GlobalException("只能对待关联的制令单操作关联工艺");
        }
        //生产线别
        String productionLine = spunlaceOrder.getProductionLineDict();
        //物料编码
        String materialCode = spunlaceOrder.getMaterialCode();

        //查询当前线别下该物料是否存在工艺卡
        ProcessSheet processSheet = processSheetMapper.selectOne(new QueryWrapper<ProcessSheet>().lambda().eq(ProcessSheet::getProductionLine, productionLine).eq(ProcessSheet::getMaterialCode, materialCode));

        if (processSheet == null) {
            throw new GlobalException("当前线别不存在工艺卡，请先配置工艺卡");
        }

        PublicProcessDto publicProcessDto = processSheetService.getView(processSheet.getId());

        if (publicProcessDto == null) {
            throw new GlobalException("当前线别无工艺卡模板，请先配置工艺卡模板");
        }
        publicProcessDto.setProductionLine(spunlaceOrder.getProductionLine());
        publicProcessDto.setProductionLineDict(productionLine);
        publicProcessDto.setMaterialCode(spunlaceOrder.getMaterialCode());
        publicProcessDto.setMaterialName(spunlaceOrder.getMaterialName());
        publicProcessDto.setMaterialRatio(spunlaceOrder.getMaterialRatio());
        publicProcessDto.setThick(spunlaceOrder.getThick());
        publicProcessDto.setMaterialGheavy(spunlaceOrder.getMaterialGheavy());
        publicProcessDto.setCustomerCode(spunlaceOrder.getCustomerCode());
        publicProcessDto.setCustomerName(spunlaceOrder.getCustomerName());
        publicProcessDto.setId(id);
        return publicProcessDto;
    }

    /**
     * 关联工艺保存
     *
     * @param publicProcessVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processSave(PublicProcessVo publicProcessVo) {

        //获取当前制令单信息
        SpunlaceOrderDto spunlaceOrder = spunlaceOrderMapper.selectSpunlace(publicProcessVo.getId());

        ProcessSheet processSheet = processSheetMapper.selectById(publicProcessVo.getProcessCardId());
        //修改工艺卡名称和工艺流程
        processSheet.setFlowId(publicProcessVo.getFlowId());
        processSheet.setProcessCardName(publicProcessVo.getProcessCardName());
        boolean save = processSheetService.updateById(processSheet);

        //修改工艺卡关联设备和属性
        if (save) {
            //获取工艺卡编码
            String processCardCoding = processSheet.getProcessCardCoding();

            //删除工艺卡设备和属性
            //获取工艺卡设备关联表
            List<ProcessTempleteDrviceCard> processTempleteDrviceList = processTempleteDrviceCardMapper.selectList(new QueryWrapper<ProcessTempleteDrviceCard>().lambda().eq(ProcessTempleteDrviceCard::getProcessTempleteId, processCardCoding));

            //设备
            List<Long> arrayList = new ArrayList<>();
            for (ProcessTempleteDrviceCard processTempleteDrvice : processTempleteDrviceList) {
                arrayList.add(processTempleteDrvice.getId());
                // List<ProcessPropertyCard> processPropertyList = processPropertyCardMapper.selectList(new QueryWrapper<ProcessPropertyCard>().lambda().eq(ProcessPropertyCard::getTempleteDrviceId, processTempleteDrvice.getId()));
                //
                // //删除设备属性表
                // processPropertyCardMapper.deleteBatchIds(processPropertyList);
            }
            processPropertyCardMapper.deleteByArrayList(arrayList);
            //删除设备工艺表
            int delete = processTempleteDrviceCardMapper.deleteBatchIds(processTempleteDrviceList);

            //关联的数据保存到工艺卡日志中
            ProcessCardLog processCardLog = new ProcessCardLog();
            processCardLog.setCreateTime(new Date());
            processCardLog.setCreateUser(SecurityUtils.getUsername());
            processCardLog.setDeptId(SecurityUtils.getDeptId());

            OperationProcess operationProcess = operationProcessMapper.selectOne(new QueryWrapper<OperationProcess>().lambda().eq(OperationProcess::getId, processSheet.getFlowId()));

            processCardLog.setFlowName(operationProcess.getFlowName());
            processCardLog.setMaterialCode(spunlaceOrder.getMaterialCode());
            processCardLog.setMaterialName(spunlaceOrder.getMaterialName());
            processCardLog.setPmMoNumber(spunlaceOrder.getSpunlaceOrderNumber());
            processCardLog.setProcessCardCoding(publicProcessVo.getProcessCardCoding());
            processCardLog.setProcessCardName(publicProcessVo.getProcessCardName());
            processCardLog.setProductionLine(publicProcessVo.getProductionLine());
            boolean logFalg = processCardLogService.save(processCardLog);

            if (delete > 0) {


                List<ProcessCardTempleteVo> list = publicProcessVo.getList();


                for (ProcessCardTempleteVo processCardTempleteVo : list) {
                    //保存工艺卡模板关联设备
                    ProcessTempleteDrviceCard processTempleteDrvice = new ProcessTempleteDrviceCard();
                    //添加设备编码
                    processTempleteDrvice.setDrviceCode(processCardTempleteVo.getDeviceCode());
                    //添加工艺卡模板id
                    processTempleteDrvice.setProcessTempleteId(processSheet.getProcessCardCoding());

                    //保存工艺设备关联表
                    processTempleteDrviceCardService.save(processTempleteDrvice);
                    //-----------工艺卡日志
                    //保存工艺卡关联设备
                    ProcessTempleteDrviceLog processTempleteDrvicelog = new ProcessTempleteDrviceLog();
                    //添加设备编码
                    processTempleteDrvicelog.setDrviceCode(processCardTempleteVo.getDeviceCode());
                    //添加工艺编码
                    processTempleteDrvicelog.setProcessTempleteId(processCardLog.getId());

                    //保存工艺设备关联表
                    processTempleteDrviceLogService.save(processTempleteDrvicelog);


                    //设备属性集合
                    List<ProcessPropertyVo> processList = processCardTempleteVo.getProcessList();
                    List<ProcessPropertyCard> processPropertyList = new ArrayList<>();
                    //工艺卡日志集合
                    List<ProcessPropertyLog> processPropertyLogList = new ArrayList<>();
                    for (ProcessPropertyVo processPropertyVo : processList) {
                        ProcessPropertyCard processProperty = new ProcessPropertyCard();
                        processProperty.setProperty(processPropertyVo.getDeviceAddedit());
                        processProperty.setValue(processPropertyVo.getValue());
                        processProperty.setTempleteDrviceId(processTempleteDrvice.getId());
                        processPropertyList.add(processProperty);

                        //-------------工艺卡日志
                        ProcessPropertyLog processPropertyLog = new ProcessPropertyLog();
                        processPropertyLog.setProperty(processPropertyVo.getDeviceAddedit());
                        processPropertyLog.setValue(processPropertyVo.getValue());
                        processPropertyLog.setTempleteDrviceId(processTempleteDrvicelog.getId());
                        processPropertyLogList.add(processPropertyLog);
                    }
                    processPropertyCardService.saveBatch(processPropertyList);
                    processPropertyLogService.saveBatch(processPropertyLogList);
                }
            }
            //修改工艺卡编码
            SpunlaceOrder spunlaceOrder1 = spunlaceOrderMapper.selectById(publicProcessVo.getId());

            //关联工艺后，校验此物料在“检验方案配置”页面是否存在检验方案。如果不存在：单据状态变为“质量标准”；
            QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();

            qualitySchemeConfigurationVo.setItemRank(2);//FAI
            qualitySchemeConfigurationVo.setCategory(4);//类别：成品
            qualitySchemeConfigurationVo.setProductionLevel(2);
            MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, spunlaceOrder1.getMaterialCode()));
            qualitySchemeConfigurationVo.setMaterialCategory(Long.valueOf(materialFinished.getMaterialType()));
            qualitySchemeConfigurationVo.setMaterialCode(spunlaceOrder1.getMaterialCode());

            boolean flagQuality=false;

            if ("1".equals(spunlaceOrder.getQualityStandard())){
                flagQuality = qualityFeginService.check(qualitySchemeConfigurationVo);
            }else{
                flagQuality = true;
            }



            //标签
            AjaxResult ajaxResult = feignService.typeList(2);
            if ("500".equals(ajaxResult.get("code"))) {
                throw new GlobalException("请先配置标签模板");
            }

            List<SysPrintTemplateDto> sysDocument = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), SysPrintTemplateDto.class);

            if (sysDocument.size()==0){
                throw new GlobalException("请先配置标签模板");
            }

            if (sysDocument == null) {
                throw new GlobalException("请先配置标签模板");
            }

            //如果已配置
            if (flagQuality) {
                //如果存在质量标准，判断水刺类型标签是否只有一个，如只存在单个标签，单据状态变为“待上线”或者”生产中“，如存在多个标签，单据状态变为标签绑定

                //如果水刺类别标签大于1个
                if (sysDocument.size() > 1) {
                    //修改单据状态为标签绑定
                    spunlaceOrder1.setDocumentStatus("7");

                } else {
                    //修改单据状态为待上线或者生产中
                    //判断当前线别是否存在生产中的指令单
                    List<SpunlaceOrder> spunlaceOrders = spunlaceOrderMapper.selectList(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getProductionLine, spunlaceOrder1.getProductionLine()).eq(SpunlaceOrder::getDocumentStatus, 1));
                    if (spunlaceOrders.size() > 0) {
                        //修改复产指令单为待上线
                        spunlaceOrder1.setPrintId(sysDocument.get(0).getPrintId());
                        spunlaceOrder1.setDocumentStatus("4");
                        //质量标准开关开启
                        spunlaceOrder1.setQualityStandard("1");
                    } else {
                        //设置单据状态为生产中
                        spunlaceOrder1.setDocumentStatus("1");

                        String spunlaceOrderNumber = spunlaceOrder1.getSpunlaceOrderNumber();
                        //查询生产领料数据
                        AjaxResult ajaxResult2 = storageFegin.spunlaceNumber(spunlaceOrderNumber);
                        List<StockOutInfoDto> data = JSONArray.parseArray(JSON.toJSONString(ajaxResult2.get("data")), StockOutInfoDto.class);

                        if(data.size() != 0){
                            List<FeedRecord> resultList = new ArrayList<>();
                            for(StockOutInfoDto entity : data){
                                FeedRecord feedRecord = new FeedRecord();
                                feedRecord.setFeedOrderNumber(spunlaceOrder1.getSpunlaceOrderNumber());
                                feedRecord.setLineCode(spunlaceOrder1.getProductionLine());
                                feedRecord.setMaterialCode(entity.getMaterialCode());
                                if (spunlaceOrder1.getBomWeight()!=null){
                                    feedRecord.setDeliveryWeight(entity.getPlannedWeight());
                                }

                                feedRecord.setCreateBy(SecurityUtils.getUsername());
                                feedRecord.setFeedType("1");
                                feedRecord.setMaterialName(materialFinished.getMaterialName());
                                feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
                                resultList.add(feedRecord);
                            }
                            iFeedRecordService.insertBatchRecord(resultList);
//                            iFeedRecordService.insertFeedRecord(feedRecord);
                        }

//                        feedRecord.setFeedOrderNumber(spunlaceOrder1.getSpunlaceOrderNumber());
//                        feedRecord.setLineCode(spunlaceOrder1.getProductionLine());
//                        feedRecord.setMaterialCode(spunlaceOrder1.getMaterialCode());
//
//                        if (spunlaceOrder1.getBomWeight()!=null) {
//                            feedRecord.setDeliveryWeight(Double.parseDouble(spunlaceOrder1.getBomWeight()));
//                        }
//
//                        feedRecord.setCreateBy(SecurityUtils.getUsername());
//                        feedRecord.setFeedType("1");
//
//                        MaterialFinished materialFinished11 = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, spunlaceOrder1.getMaterialCode()));
//
//                        feedRecord.setMaterialName(materialFinished11.getMaterialName());
//                        feedRecord.setMaterialSpec(materialFinished11.getMaterialSpec());
//
//                        iFeedRecordService.insertFeedRecord(feedRecord);


                        spunlaceOrder1.setActualStartTime(new Date());

                        //回传排程实际开工时间
                        BackAdjustVo backAdjustVo = new BackAdjustVo();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                        backAdjustVo.setActualStartTime(simpleDateFormat.format(new Date()));
                        backAdjustVo.setExecutionDoc(spunlaceOrder1.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
                        backAdjustVo.setExecutionState(3);//生产中
                        AjaxResult ajaxResult1 = schedulingPlanFeignService.backAdjust(backAdjustVo);
                        if ("500".equals(ajaxResult1.get("code"))) {
                            throw new GlobalException("关联失败");
                        }

                        //绑定标签
                        spunlaceOrder1.setPrintId(sysDocument.get(0).getPrintId());
                        //水刺产出列表上线
                        SpunlaceOutputVo spunlaceOutputVo = new SpunlaceOutputVo();

                        spunlaceOutputVo.setProductionLine(spunlaceOrder1.getProductionLine());//生产线别
                        spunlaceOutputVo.setWorkshop(spunlaceOrder1.getWorkshop());
                        spunlaceOutputVo.setSpunlaceOrderNumber(spunlaceOrder1.getSpunlaceOrderNumber());//制令单号
                        spunlaceOutputVo.setProductionStatus("1");//生产状态  生产中
                        spunlaceOutputVo.setMaterialCode(spunlaceOrder1.getMaterialCode());//物料编码
                        spunlaceOutputVo.setMotherBreadth(spunlaceOrder1.getMotherBreadth());//母卷幅宽
                        spunlaceOutputVo.setRollingDiameter(spunlaceOrder1.getRollingDiameter());//卷径
                        spunlaceOutputVo.setThick(spunlaceOrder1.getThick());
                        spunlaceOutputVo.setProductionPlanNumber(spunlaceOrder1.getProductionPlanNumber());//生产计划单号
                        spunlaceOutputVo.setPlanWeight(spunlaceOrder1.getPlanWeight());
                        spunlaceOutputService.add(spunlaceOutputVo);
                        //质量标准开关开启
                        spunlaceOrder1.setQualityStandard("1");
                    }
                }
            } else {
                //单据状态变为“质量标准
                spunlaceOrder1.setDocumentStatus("6");
                if (sysDocument.size() == 1) {
                    //修改单据状态为标签绑定
                    spunlaceOrder1.setPrintId(sysDocument.get(0).getPrintId());

                }
            }



           /* if (logFalg){

                    List<ProcessCardTempleteVo> list = publicProcessVo.getList();

                    for (ProcessCardTempleteVo processCardTempleteVo : list) {
                        //保存工艺卡关联设备
                        ProcessTempleteDrviceLog processTempleteDrvicelog = new ProcessTempleteDrviceLog();
                        //添加设备编码
                        processTempleteDrvicelog.setDrviceCode(processCardTempleteVo.getDrviceCode());
                        //添加工艺编码
                        processTempleteDrvicelog.setProcessTempleteId(processCardLog.getId());

                        //保存工艺设备关联表
                        processTempleteDrviceLogService.save(processTempleteDrvicelog);

                        //设备属性集合
                        List<ProcessPropertyVo> processList = processCardTempleteVo.getProcessList();
                        List<ProcessPropertyLog> processPropertyList = new ArrayList<>();
                        for (ProcessPropertyVo processPropertyVo : processList) {
                            ProcessPropertyLog processPropertyLog = new ProcessPropertyLog();
                            processPropertyLog.setProperty(processPropertyVo.getDrviceAddedit());
                            processPropertyLog.setValue(processPropertyVo.getValue());
                            processPropertyLog.setTempleteDrviceId(processTempleteDrvicelog.getId());
                            processPropertyList.add(processPropertyLog);
                        }
                        processPropertyLogService.saveBatch(processPropertyList);
                    }
               }*/
            spunlaceOrder1.setProcessCardCoding(publicProcessVo.getProcessCardCoding());
            updateById(spunlaceOrder1);
        }
        return save;
    }

    /**
     * 工艺确认
     *
     * @param publicProcessVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processAffirm(PublicProcessVo publicProcessVo) {

        //获取当前制令单信息
        SpunlaceOrderDto spunlaceOrder = spunlaceOrderMapper.selectSpunlace(publicProcessVo.getId());

        ProcessSheet processSheet = processSheetMapper.selectById(publicProcessVo.getProcessCardId());
        //修改工艺卡名称和工艺流程
        processSheet.setFlowId(publicProcessVo.getFlowId());
        processSheet.setProcessCardName(publicProcessVo.getProcessCardName());
        boolean save = processSheetService.updateById(processSheet);

        //修改工艺卡关联设备和属性
        if (save) {
            //获取工艺卡编码
            String processCardCoding = processSheet.getProcessCardCoding();

            //删除工艺卡设备和属性
            //获取工艺卡设备关联表
            List<ProcessTempleteDrviceCard> processTempleteDrviceList = processTempleteDrviceCardMapper.selectList(new QueryWrapper<ProcessTempleteDrviceCard>().lambda().eq(ProcessTempleteDrviceCard::getProcessTempleteId, processCardCoding));

            //设备
            List<Long> arrayList = new ArrayList<>();
            for (ProcessTempleteDrviceCard processTempleteDrvice : processTempleteDrviceList) {
                arrayList.add(processTempleteDrvice.getId());
                // List<ProcessPropertyCard> processPropertyList = processPropertyCardMapper.selectList(new QueryWrapper<ProcessPropertyCard>().lambda().eq(ProcessPropertyCard::getTempleteDrviceId, processTempleteDrvice.getId()));
                //
                // //删除设备属性表
                // processPropertyCardMapper.deleteBatchIds(processPropertyList);
            }
            processPropertyCardMapper.deleteByArrayList(arrayList);
            //删除设备工艺表
            int delete = processTempleteDrviceCardMapper.deleteBatchIds(processTempleteDrviceList);

            //关联的数据保存到工艺卡日志中
            ProcessCardLog processCardLog = new ProcessCardLog();
            processCardLog.setCreateTime(new Date());
            processCardLog.setCreateUser(SecurityUtils.getUsername());
            processCardLog.setDeptId(SecurityUtils.getDeptId());

            OperationProcess operationProcess = operationProcessMapper.selectOne(new QueryWrapper<OperationProcess>().lambda().eq(OperationProcess::getId, processSheet.getFlowId()));

            processCardLog.setFlowName(operationProcess.getFlowName());
            processCardLog.setMaterialCode(spunlaceOrder.getMaterialCode());
            processCardLog.setMaterialName(spunlaceOrder.getMaterialName());
            processCardLog.setPmMoNumber(spunlaceOrder.getSpunlaceOrderNumber());
            processCardLog.setProcessCardCoding(publicProcessVo.getProcessCardCoding());
            processCardLog.setProcessCardName(publicProcessVo.getProcessCardName());
            processCardLog.setProductionLine(publicProcessVo.getProductionLine());
            boolean logFalg = processCardLogService.save(processCardLog);

            if (delete > 0) {


                List<ProcessCardTempleteVo> list = publicProcessVo.getList();


                for (ProcessCardTempleteVo processCardTempleteVo : list) {
                    //保存工艺卡模板关联设备
                    ProcessTempleteDrviceCard processTempleteDrvice = new ProcessTempleteDrviceCard();
                    //添加设备编码
                    processTempleteDrvice.setDrviceCode(processCardTempleteVo.getDeviceCode());
                    //添加工艺卡模板id
                    processTempleteDrvice.setProcessTempleteId(processSheet.getProcessCardCoding());

                    //保存工艺设备关联表
                    processTempleteDrviceCardService.save(processTempleteDrvice);
                    //-----------工艺卡日志
                    //保存工艺卡关联设备
                    ProcessTempleteDrviceLog processTempleteDrvicelog = new ProcessTempleteDrviceLog();
                    //添加设备编码
                    processTempleteDrvicelog.setDrviceCode(processCardTempleteVo.getDeviceCode());
                    //添加工艺编码
                    processTempleteDrvicelog.setProcessTempleteId(processCardLog.getId());

                    //保存工艺设备关联表
                    processTempleteDrviceLogService.save(processTempleteDrvicelog);


                    //设备属性集合
                    List<ProcessPropertyVo> processList = processCardTempleteVo.getProcessList();
                    List<ProcessPropertyCard> processPropertyList = new ArrayList<>();
                    //工艺卡日志集合
                    List<ProcessPropertyLog> processPropertyLogList = new ArrayList<>();
                    for (ProcessPropertyVo processPropertyVo : processList) {
                        ProcessPropertyCard processProperty = new ProcessPropertyCard();
                        processProperty.setProperty(processPropertyVo.getDeviceAddedit());
                        processProperty.setValue(processPropertyVo.getValue());
                        processProperty.setTempleteDrviceId(processTempleteDrvice.getId());
                        processPropertyList.add(processProperty);

                        //-------------工艺卡日志
                        ProcessPropertyLog processPropertyLog = new ProcessPropertyLog();
                        processPropertyLog.setProperty(processPropertyVo.getDeviceAddedit());
                        processPropertyLog.setValue(processPropertyVo.getValue());
                        processPropertyLog.setTempleteDrviceId(processTempleteDrvicelog.getId());
                        processPropertyLogList.add(processPropertyLog);
                    }
                    processPropertyCardService.saveBatch(processPropertyList);
                    processPropertyLogService.saveBatch(processPropertyLogList);
                }
            }
        }
            //修改工艺卡编码
            SpunlaceOrder spunlaceOrder1 = spunlaceOrderMapper.selectById(publicProcessVo.getId());


       // processSave(publicProcessVo);
        //2.工艺确认后，表格中“工艺确认”项变为开启
            spunlaceOrder1.setProcessCardCoding(publicProcessVo.getProcessCardCoding());
            updateById(spunlaceOrder1);

            spunlaceOrder1.setProcessValidation("1");
        return updateById(spunlaceOrder1);

    }

    /**
     * 工艺卡回显
     * @param id
     * @return
     */
    @Override
    public PublicProcessDto processAffirmView(Long id) {
        //获取当前制令单信息
        SpunlaceOrderDto spunlaceOrder = spunlaceOrderMapper.selectSpunlace(id);
        //查询当前水刺产出明细中是否有检验完成且状态为合格的单据明细
        List<SpunlaceOutputDetail> spunlaceOutputDetails = spunlaceOutputDetailMapper.selectList(new QueryWrapper<SpunlaceOutputDetail>().lambda().eq(SpunlaceOutputDetail::getCheckStatus, 2).eq(SpunlaceOutputDetail::getCheckResult, 1).eq(SpunlaceOutputDetail::getSpunlaceOrderNumber, spunlaceOrder.getSpunlaceOrderNumber()));
        if (spunlaceOutputDetails.size() == 0) {
            throw new GlobalException("只能对”首检“合格的制令单进行工艺确认");
        }
        //生产线别
        String productionLine = spunlaceOrder.getProductionLineDict();
        //物料编码
        String materialCode = spunlaceOrder.getMaterialCode();

        //查询当前线别下该物料是否存在工艺卡
        ProcessSheet processSheet = processSheetMapper.selectOne(new QueryWrapper<ProcessSheet>().lambda().eq(ProcessSheet::getProductionLine, productionLine).eq(ProcessSheet::getMaterialCode, materialCode));

        PublicProcessDto publicProcessDto = processSheetService.getView(processSheet.getId());

        publicProcessDto.setProductionLine(spunlaceOrder.getProductionLine());
        publicProcessDto.setProductionLineDict(productionLine);
        publicProcessDto.setMaterialCode(spunlaceOrder.getMaterialCode());
        publicProcessDto.setMaterialName(spunlaceOrder.getMaterialName());
        publicProcessDto.setMaterialRatio(spunlaceOrder.getMaterialRatio());
        publicProcessDto.setThick(spunlaceOrder.getThick());
        publicProcessDto.setMaterialGheavy(spunlaceOrder.getMaterialGheavy());
        publicProcessDto.setCustomerCode(spunlaceOrder.getCustomerCode());
        publicProcessDto.setCustomerName(spunlaceOrder.getCustomerName());
        publicProcessDto.setId(id);
        return publicProcessDto;
    }

    /**
     * 新增执行单
     *
     * @param publicScheduling
     * @return void
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addOrderCutScheduling(PublicScheduling publicScheduling) throws Exception {
        long deptId = SecurityUtils.getDeptId();
        publicScheduling.setDeptId(deptId);
        String name = SecurityUtils.getUsername();
        publicScheduling.setCreateMan(name);
        publicScheduling.setLssuedMan(name);
        String pc = publicScheduling.getExecutionDoc();
        String replace = pc.replace("PC", "SC");
        publicScheduling.setSpunlaceOrderNumber(pc.replace("PC", "SC"));
        //通过线别编码查询车间编码and车间id
        String lineCode = publicScheduling.getProductionLine();
        LineWorkShop lineWork = shopModelingMapper.getWorkshopInfo(lineCode);
        publicScheduling.setWorkshop(lineWork.getModelingCode());
        publicScheduling.setWorkShopId(lineWork.getModelingId());

        //销售订单号
        String orderNumber = publicScheduling.getProductionPlanNumber().replaceAll("SJ", "XS");
        String[] split = orderNumber.split(",");

        StringBuilder stringBuilder = new StringBuilder();
        for (String s : split) {
            if (s.length()>11){
                String substring = s.substring(0, 11);
                stringBuilder.append(substring).append(",");
            }else {
                stringBuilder.append(s).append(",");
            }
        }
        StringBuilder stringBuilder1 = stringBuilder.deleteCharAt(stringBuilder.length() - 1);

        publicScheduling.setSaleNumber(stringBuilder1.toString());
        //关联工艺后，校验此物料在“检验方案配置”页面是否存在检验方案。如果不存在：单据状态变为“质量标准”；
        QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();

        qualitySchemeConfigurationVo.setItemRank(2);//FAI
        qualitySchemeConfigurationVo.setCategory(4);//类别：成品
        qualitySchemeConfigurationVo.setProductionLevel(2);//阶别
        MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, publicScheduling.getMaterialCode()));
        qualitySchemeConfigurationVo.setMaterialCategory(Long.valueOf(materialFinished.getMaterialType()));
        qualitySchemeConfigurationVo.setMaterialCode(publicScheduling.getMaterialCode());

        //通过分切车间编码查出分切车间id
        SysShopModelingDto workshopInfo = shopModelingMapper.getSysShopModeling(publicScheduling.getSlittingCode());

        boolean flagQuality = qualityFeginService.check(qualitySchemeConfigurationVo);

        //如果已配置
        if (flagQuality) {
            //开启质量标准
            publicScheduling.setQualityStandard(1);
        } else {
            publicScheduling.setQualityStandard(2);
        }

        publicScheduling.setCreateMan(SecurityUtils.getUsername());
        publicScheduling.setCreateTime(new Date());

        //去掉排程下达卷径和厚度用逗号分割
        publicScheduling.setRollingDiameter(publicScheduling.getRollingDiameter().split(",")[0]);
        publicScheduling.setThick(publicScheduling.getThick().split(",")[0]);

        int is = spunlaceOrderMapper.addOrderCutScheduling(publicScheduling);
        //新增水刺的同时 生成分切单
        if (is > 0) {
            CutOrdersDocumentVo vo = new CutOrdersDocumentVo();
            vo.setSplittingOrderNumber(pc.replace("PC", "FQ"));
            vo.setProductStatus(1);
            vo.setMaterialCode(publicScheduling.getMaterialCode());
            //   vo.setMaterialName(publicScheduling.get);
            vo.setWidth(publicScheduling.getMotherBreadth());//幅宽
            vo.setPlanWeight(publicScheduling.getPlanWeight());

            //vo.setWorkshopId(lineWork.getModelingId());
            vo.setWorkshopId(workshopInfo.getModelingId());
            vo.setDeptId(deptId);
            vo.setOrderRemark(publicScheduling.getOrderRemake());
            vo.setPlanRemark(publicScheduling.getPlanRemake());
            vo.setSchedulRemark(publicScheduling.getScheduleRemake());
            vo.setCustomerCode(publicScheduling.getCustomerCode());
            vo.setModelingName(lineWork.getModelingCode());
            vo.setWindingDiameter(publicScheduling.getRollingDiameter());

            vo.setProductionPlanSheet(publicScheduling.getProductionPlanNumber());//生产计划单
            //订单号
            vo.setSaleNumber(publicScheduling.getSaleNumber());
            //幅宽
            vo.setWidth(publicScheduling.getSlittingWidthCloth());
            //包装要求
            vo.setPackingRequirement(publicScheduling.getPacking());
            //每包小卷数
            vo.setSmallRollNum(publicScheduling.getNumberRolls());
            //卷径
            vo.setWindingDiameter(String.valueOf(publicScheduling.getRollingDiameter()));
            vo.setSaleNumber(publicScheduling.getSaleNumber());

            //lineTypeName
            //  productStatus
            boolean flag = cutOrdersDocumentService.add(vo);
            if (!flag) {
                throw new SQLException("生成失败");
            }
        }
        return is;
    }

    /**
     * 水刺和分切制令单列表
     *
     * @return
     */
    @Override
    public List<ScFqDto> getMoOrderList(String moNumber) {
        List<ScFqDto> list = spunlaceOrderMapper.selectScFqList(moNumber);
        return list;
    }

    /**
     * feign级调用，品质在配置检验方案之后修改指令单的单据状态
     *
     * @param editQualityOrderVo
     * @return
     */
    @Override
    public boolean editQualityOrder(EditQualityOrderVo editQualityOrderVo) {
        String materialCode = editQualityOrderVo.getMaterialCode();
        String materialType = editQualityOrderVo.getMaterialType();
        AjaxResult ajaxResult = feignService.typeList(2);
        List<SysPrintTemplateDto> sysDocument = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), SysPrintTemplateDto.class);

        if (sysDocument.size()==0){
            throw new GlobalException("请先配置标签模板");
        }

        boolean flag = false;

        if (materialCode != "" && materialCode != null) {

            List<Long> ids = spunlaceOrderMapper.selectQualityOrder(materialCode);

            List arrayList = new ArrayList<SpunlaceOrder>();

            for (Long id : ids) {

                SpunlaceOrder spunlaceOrder = getById(id);
                //判断单据状态是否是质量标准
                if ("6".equals(spunlaceOrder.getDocumentStatus())) {
                    //判断是否存在多个标签
                    if (sysDocument.size() > 1) {
                        //否则改为标签绑定
                        spunlaceOrder.setDocumentStatus("7");
                        //修改质量标准状态为开启
                        spunlaceOrder.setQualityStandard("1");
                        flag = updateById(spunlaceOrder);

                        //arrayList.add(spunlaceOrder);
                    } else {
                        //判断当前线别是否存在生产中的指令单
                        List<SpunlaceOrder> spunlaceOrders = spunlaceOrderMapper.selectList(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getDocumentStatus, 1).eq(SpunlaceOrder::getProductionLine, spunlaceOrder.getProductionLine()));
                        if (spunlaceOrders.size() > 0) {
                            //修改水刺指令单为待上线
                            spunlaceOrder.setDocumentStatus("4");
                            spunlaceOrder.setPrintId(sysDocument.get(0).getPrintId());
                            //修改质量标准状态为开启
                            spunlaceOrder.setQualityStandard("1");
                            flag = updateById(spunlaceOrder);
                            //arrayList.add(spunlaceOrder);
                        } else {
                            //查询当前线别下状态是质量标准且物料编码是品质配置物料编码，且开工时间最近的生成执行单
                            SpunlaceOrder spunlaceOrder1 = spunlaceOrderMapper.selectQualityCodeProcuction(materialCode, spunlaceOrder.getProductionLine());

                            spunlaceOrder1.setPrintId(sysDocument.get(0).getPrintId());

                            //水刺制令单改为生产中
                            spunlaceOrder1.setDocumentStatus("1");

                            String spunlaceOrderNumber = spunlaceOrder1.getSpunlaceOrderNumber();
                            //查询生产领料数据
                            AjaxResult ajaxResult2 = storageFegin.spunlaceNumber(spunlaceOrderNumber);
                            List<StockOutInfoDto> data = JSONArray.parseArray(JSON.toJSONString(ajaxResult2.get("data")), StockOutInfoDto.class);

                            if(data.size() != 0){
                                List<FeedRecord> resultList = new ArrayList<>();
                                for(StockOutInfoDto entity : data){
                                    FeedRecord feedRecord = new FeedRecord();
                                    feedRecord.setFeedOrderNumber(spunlaceOrder1.getSpunlaceOrderNumber());
                                    feedRecord.setLineCode(spunlaceOrder1.getProductionLine());
                                    feedRecord.setMaterialCode(entity.getMaterialCode());
                                    if (spunlaceOrder1.getBomWeight()!=null){
                                        feedRecord.setDeliveryWeight(entity.getPlannedWeight());
                                    }

                                    feedRecord.setCreateBy(SecurityUtils.getUsername());
                                    feedRecord.setFeedType("1");
//                            feedRecord.setMaterialName(materialFinished.getMaterialName());
//                            feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
                                    resultList.add(feedRecord);
                                }
                                iFeedRecordService.insertBatchRecord(resultList);
//                            iFeedRecordService.insertFeedRecord(feedRecord);
                            }

//                            FeedRecord feedRecord = new FeedRecord();
//
//                            feedRecord.setFeedOrderNumber(spunlaceOrder1.getSpunlaceOrderNumber());
//                            feedRecord.setLineCode(spunlaceOrder1.getProductionLine());
//                            feedRecord.setMaterialCode(spunlaceOrder1.getMaterialCode());
//
//                            if (spunlaceOrder1.getBomWeight()!=null) {
//                                feedRecord.setDeliveryWeight(Double.parseDouble(spunlaceOrder1.getBomWeight()));
//                            }
//
//                            feedRecord.setCreateBy(SecurityUtils.getUsername());
//                            feedRecord.setFeedType("1");
//
//                            MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, spunlaceOrder1.getMaterialCode()));
//
//                            feedRecord.setMaterialName(materialFinished.getMaterialName());
//                            feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
//
//                            iFeedRecordService.insertFeedRecord(feedRecord);


                            spunlaceOrder1.setActualStartTime(new Date());
                            //回传排程实际开工时间
                            BackAdjustVo backAdjustVo = new BackAdjustVo();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                            backAdjustVo.setActualStartTime(simpleDateFormat.format(new Date()));
                            backAdjustVo.setExecutionDoc(spunlaceOrder1.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
                            backAdjustVo.setExecutionState(3);//生产中

                            AjaxResult ajaxResult1 = schedulingPlanFeignService.backAdjust(backAdjustVo);
                            if ("500".equals(ajaxResult1.get("code"))) {
                                throw new GlobalException("关结失败");
                            }

                            //修改质量标准状态为开启
                            spunlaceOrder1.setQualityStandard("1");

                            flag = updateById(spunlaceOrder1);
                            //arrayList.add(spunlaceOrder1);

                            //水刺产出列表上线
                            SpunlaceOutputVo spunlaceOutputVo = new SpunlaceOutputVo();
                            spunlaceOutputVo.setProductionLine(spunlaceOrder1.getProductionLine());//生产线别
                            spunlaceOutputVo.setWorkshop(spunlaceOrder1.getWorkshop());
                            spunlaceOutputVo.setSpunlaceOrderNumber(spunlaceOrder1.getSpunlaceOrderNumber());//制令单号
                            spunlaceOutputVo.setProductionStatus("1");//生产状态  生产中
                            spunlaceOutputVo.setMaterialCode(spunlaceOrder1.getMaterialCode());//物料编码
                            spunlaceOutputVo.setMotherBreadth(spunlaceOrder1.getMotherBreadth());//母卷幅宽
                            spunlaceOutputVo.setRollingDiameter(spunlaceOrder1.getRollingDiameter());//卷径
                            spunlaceOutputVo.setThick(spunlaceOrder1.getThick());
                            spunlaceOutputVo.setProductionPlanNumber(spunlaceOrder1.getProductionPlanNumber());//生产计划单号
                            spunlaceOutputVo.setPlanWeight(spunlaceOrder1.getPlanWeight());
                            spunlaceOutputVo.setPrintId(sysDocument.get(0).getPrintId());
                            spunlaceOutputService.add(spunlaceOutputVo);

                        }

                    }
                }

            }


        }

        if (materialType != "" && materialType != null) {
            List<Long> ids = spunlaceOrderMapper.selectMaterialType(materialType);

            List arrayList = new ArrayList<SpunlaceOrder>();

            for (Long id : ids) {
                SpunlaceOrder spunlaceOrder = getById(id);

                //判断单据状态是否是质量标准
                if ("6".equals(spunlaceOrder.getDocumentStatus())) {
                    //判断是否存在多个标签
                    if (sysDocument.size() > 1) {
                        //否则改为标签绑定
                        spunlaceOrder.setDocumentStatus("7");

                        //修改质量标准状态为开启
                        spunlaceOrder.setQualityStandard("1");

                        flag = updateById(spunlaceOrder);
                    } else {
                        //判断当前线别是否存在生产中的指令单
                        List<SpunlaceOrder> spunlaceOrders = spunlaceOrderMapper.selectList(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getDocumentStatus, 1).eq(SpunlaceOrder::getProductionLine, spunlaceOrder.getProductionLine()));
                        if (spunlaceOrders.size() > 0) {
                            //修改水刺指令单为待上线
                            spunlaceOrder.setDocumentStatus("4");

                            //修改质量标准状态为开启
                            spunlaceOrder.setQualityStandard("1");

                            spunlaceOrder.setPrintId(sysDocument.get(0).getPrintId());

                            flag = updateById(spunlaceOrder);
                        } else {
                            //查询当前线别下状态是质量标准且物料类别是品质配置物料类别，且开工时间最近的生成执行单
                            SpunlaceOrder spunlaceOrder1 = spunlaceOrderMapper.selectQualityTypeProcuction(materialType, spunlaceOrder.getProductionLine());

                            //水刺制令单改为生产中
                            spunlaceOrder1.setDocumentStatus("1");

                            String spunlaceOrderNumber = spunlaceOrder1.getSpunlaceOrderNumber();
                            //查询生产领料数据
                            AjaxResult ajaxResult2 = storageFegin.spunlaceNumber(spunlaceOrderNumber);
                            List<StockOutInfoDto> data = JSONArray.parseArray(JSON.toJSONString(ajaxResult2.get("data")), StockOutInfoDto.class);

                            if(data.size() != 0){
                                List<FeedRecord> resultList = new ArrayList<>();
                                for(StockOutInfoDto entity : data){
                                    FeedRecord feedRecord = new FeedRecord();
                                    feedRecord.setFeedOrderNumber(spunlaceOrder1.getSpunlaceOrderNumber());
                                    feedRecord.setLineCode(spunlaceOrder1.getProductionLine());
                                    feedRecord.setMaterialCode(entity.getMaterialCode());
                                    if (spunlaceOrder1.getBomWeight()!=null){
                                        feedRecord.setDeliveryWeight(entity.getPlannedWeight());
                                    }

                                    feedRecord.setCreateBy(SecurityUtils.getUsername());
                                    feedRecord.setFeedType("1");
//                            feedRecord.setMaterialName(materialFinished.getMaterialName());
//                            feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
                                    resultList.add(feedRecord);
                                }
                                iFeedRecordService.insertBatchRecord(resultList);
//                            iFeedRecordService.insertFeedRecord(feedRecord);
                            }

//                            FeedRecord feedRecord = new FeedRecord();
//
//                            feedRecord.setFeedOrderNumber(spunlaceOrder1.getSpunlaceOrderNumber());
//                            feedRecord.setLineCode(spunlaceOrder1.getProductionLine());
//                            feedRecord.setMaterialCode(spunlaceOrder1.getMaterialCode());
//
//                            if (spunlaceOrder1.getBomWeight()!=null) {
//                                feedRecord.setDeliveryWeight(Double.parseDouble(spunlaceOrder1.getBomWeight()));
//                            }
//
//                            feedRecord.setCreateBy(SecurityUtils.getUsername());
//                            feedRecord.setFeedType("1");
//
//                            MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, spunlaceOrder1.getMaterialCode()));
//
//                            feedRecord.setMaterialName(materialFinished.getMaterialName());
//                            feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
//
//                            iFeedRecordService.insertFeedRecord(feedRecord);


                            spunlaceOrder1.setActualStartTime(new Date());

                            //回传排程实际开工时间
                            BackAdjustVo backAdjustVo = new BackAdjustVo();
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                            backAdjustVo.setActualStartTime(simpleDateFormat.format(new Date()));
                            backAdjustVo.setExecutionDoc(spunlaceOrder1.getSpunlaceOrderNumber().replaceAll("SC", "PC"));
                            backAdjustVo.setExecutionState(3);//生产中

                            AjaxResult ajaxResult1 = schedulingPlanFeignService.backAdjust(backAdjustVo);
                            if ("500".equals(ajaxResult1.get("code"))) {
                                throw new GlobalException("关结失败");
                            }
                            //修改质量标准状态为开启
                            spunlaceOrder1.setQualityStandard("1");

                            flag = updateById(spunlaceOrder1);

                            //水刺产出列表上线
                            SpunlaceOutputVo spunlaceOutputVo = new SpunlaceOutputVo();
                            spunlaceOutputVo.setProductionLine(spunlaceOrder1.getProductionLine());//生产线别
                            spunlaceOutputVo.setWorkshop(spunlaceOrder1.getWorkshop());
                            spunlaceOutputVo.setSpunlaceOrderNumber(spunlaceOrder1.getSpunlaceOrderNumber());//制令单号
                            spunlaceOutputVo.setProductionStatus("1");//生产状态  生产中
                            spunlaceOutputVo.setMaterialCode(spunlaceOrder1.getMaterialCode());//物料编码
                            spunlaceOutputVo.setMotherBreadth(spunlaceOrder1.getMotherBreadth());//母卷幅宽
                            spunlaceOutputVo.setRollingDiameter(spunlaceOrder1.getRollingDiameter());//卷径
                            spunlaceOutputVo.setThick(spunlaceOrder1.getThick());
                            spunlaceOutputVo.setProductionPlanNumber(spunlaceOrder1.getProductionPlanNumber());//生产计划单号
                            spunlaceOutputVo.setPlanWeight(spunlaceOrder1.getPlanWeight());
                            spunlaceOutputService.add(spunlaceOutputVo);
                        }
                    }
                }

            }
        }

        return flag;
    }

    /**
     * 条码打印
     *
     * @param materialNumber
     * @param type
     * @return
     */
    @Override
    public PrintDto getProductionNumberPrint(String materialNumber, String type) {
        PrintDto printDto1 = new PrintDto();
        //水刺打印
        if ("3".equals(type)) {
            PrintDto printDto = spunlaceOutputDetailMapper.selectPrintInfo(materialNumber);
            if (printDto != null) {
                return printDto;
            } else {
                throw new GlobalException("请输入正确的产品号码");
            }

        } else if ("4".equals(type)) {
            PrintDto printDto = rollPackingMapper.selectPrintInfo(materialNumber);
            PrintDto printInfo = weighingFinishedMaterialProductMapper.getPrintInfo(printDto.getMasterVolumeNumber());
            printDto.setMaterialBatch(printInfo.getMaterialBatch());
            if (printDto != null) {
                return printDto;
            } else {
                throw new GlobalException("请输入正确的产品号码");
            }
        } else if ("5".equals(type)) {
            //网形
            List<SysDictData> typeArray = DictUtils.getDictCache("sys_of_type");
            Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

            PrintDto printDto = weighingFinishedMaterialProductMapper.selectPrintInfo(materialNumber);
            PrintDto printInfo = weighingFinishedMaterialProductMapper.getPrintInfo(printDto.getMasterVolumeNumber());
            if (printInfo != null) {
                printDto.setRollingDiameter(printInfo.getRollingDiameter());
                printDto.setRollLength(printInfo.getRollLength());
                printDto.setBreadth(printInfo.getBreadth());
                printDto.setJoint(printInfo.getJoint());
                printDto.setMaterialNet(typeMap.get(printDto.getMaterialNet()));
            }
            if (printDto != null) {
                return printDto;
            } else {
                throw new GlobalException("请输入正确的产品号码");
            }
        } else {
            return printDto1;
        }

    }

    /**
     * 根据库存的关联单号查询水刺制令单工艺卡编码
     *
     * @param wsiConnectNum
     * @return
     */
    @Override
    public SpunlaceOrderDto getProcessCardCoding(String wsiConnectNum) {
        return spunlaceOrderMapper.getProcessCardCoding(wsiConnectNum);
    }

    /**
     * 模板id
     *
     * @param printTempleteVo
     * @return
     */
    @Override
    public boolean savePrintTemplete(PrintTempleteVo printTempleteVo) {
        //查询当前水刺制令单
        SpunlaceOrder spunlaceOrder = getById(printTempleteVo.getId());
        //修改模板id
        spunlaceOrder.setPrintId(printTempleteVo.getPrintId());

        //查询当前线别是否存在生产中的单据
        List<SpunlaceOrder> spunlaceOrders = spunlaceOrderMapper.selectList(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getProductionLine, spunlaceOrder.getProductionLine()).eq(SpunlaceOrder::getDocumentStatus, 1));

        if (spunlaceOrders.size() > 0) {
            //如果有生产中的单据，修改当前状态未待上线
            spunlaceOrder.setDocumentStatus("4");
        } else {
            //如果没有生产中的单据，修改当前状态为生产中
            spunlaceOrder.setDocumentStatus("1");

            String spunlaceOrderNumber = spunlaceOrder.getSpunlaceOrderNumber();
            //查询生产领料数据
            AjaxResult ajaxResult2 = storageFegin.spunlaceNumber(spunlaceOrderNumber);
            List<StockOutInfoDto> data = JSONArray.parseArray(JSON.toJSONString(ajaxResult2.get("data")), StockOutInfoDto.class);

            if(data.size() != 0){
                List<FeedRecord> resultList = new ArrayList<>();
                for(StockOutInfoDto entity : data){
                    FeedRecord feedRecord = new FeedRecord();
                    feedRecord.setFeedOrderNumber(spunlaceOrder.getSpunlaceOrderNumber());
                    feedRecord.setLineCode(spunlaceOrder.getProductionLine());
                    feedRecord.setMaterialCode(entity.getMaterialCode());
                    if (spunlaceOrder.getBomWeight()!=null){
                        feedRecord.setDeliveryWeight(entity.getPlannedWeight());
                    }

                    feedRecord.setCreateBy(SecurityUtils.getUsername());
                    feedRecord.setFeedType("1");
//                            feedRecord.setMaterialName(materialFinished.getMaterialName());
//                            feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
                    resultList.add(feedRecord);
                }
                iFeedRecordService.insertBatchRecord(resultList);
//                            iFeedRecordService.insertFeedRecord(feedRecord);
            }

//            FeedRecord feedRecord = new FeedRecord();
//
//            feedRecord.setFeedOrderNumber(spunlaceOrder.getSpunlaceOrderNumber());
//            feedRecord.setLineCode(spunlaceOrder.getProductionLine());
//            feedRecord.setMaterialCode(spunlaceOrder.getMaterialCode());
//
//            if (spunlaceOrder.getBomWeight()!=null){
//                feedRecord.setDeliveryWeight(Double.parseDouble(spunlaceOrder.getBomWeight()));
//            }
//
//
//            feedRecord.setCreateBy(SecurityUtils.getUsername());
//            feedRecord.setFeedType("1");
//
//            MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, spunlaceOrder.getMaterialCode()));
//
//            feedRecord.setMaterialName(materialFinished.getMaterialName());
//            feedRecord.setMaterialSpec(materialFinished.getMaterialSpec());
//
//            iFeedRecordService.insertFeedRecord(feedRecord);


            //水刺产出新增数据
            //水刺产出列表上线
            SpunlaceOutputVo spunlaceOutputVo = new SpunlaceOutputVo();
            spunlaceOutputVo.setProductionLine(spunlaceOrder.getProductionLine());//生产线别
            spunlaceOutputVo.setWorkshop(spunlaceOrder.getWorkshop());
            spunlaceOutputVo.setSpunlaceOrderNumber(spunlaceOrder.getSpunlaceOrderNumber());//制令单号
            spunlaceOutputVo.setProductionStatus("1");//生产状态  生产中
            spunlaceOutputVo.setMaterialCode(spunlaceOrder.getMaterialCode());//物料编码
            spunlaceOutputVo.setMotherBreadth(spunlaceOrder.getMotherBreadth());//母卷幅宽
            spunlaceOutputVo.setRollingDiameter(spunlaceOrder.getRollingDiameter());//卷径
            spunlaceOutputVo.setThick(spunlaceOrder.getThick());
            spunlaceOutputVo.setProductionPlanNumber(spunlaceOrder.getProductionPlanNumber());//生产计划单号
            spunlaceOutputVo.setPlanWeight(spunlaceOrder.getPlanWeight());
            spunlaceOutputService.add(spunlaceOutputVo);
        }
        return updateById(spunlaceOrder);
    }


    /**
     * PDA产出列表
     *
     * @param pdaVo
     * @return
     */
    @Override
    public List<PdaDto> getPdaList(PdaVo pdaVo) {

        //产出类别（1脱脂2水刺3分切）
        String type = pdaVo.getType();
        if ("2".equals(type)) {
            List<PdaDto> pdaDtoList = spunlaceOrderMapper.selectPdaList(pdaVo);
            List<SysDictData> statusArray = DictUtils.getDictCache("spunlace_order_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (PdaDto pdaDto : pdaDtoList) {
                pdaDto.setStatusDict(statusMap.get(pdaDto.getStatus()));
            }

            return pdaDtoList;
        } else if ("3".equals(type)) {
            List<PdaDto> pdaDtos = cutOrdersDocumentService.pdaList(pdaVo);
            List<SysDictData> statusArray = DictUtils.getDictCache("splitting_order_number_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (PdaDto entity : pdaDtos) {
                entity.setStatusDict(statusMap.get(entity.getStatus()));
            }
            return pdaDtos;

        } else if("1".equals(type)){
            List<PdaDto> pdaDtos = degreasDocumentService.pdaList(pdaVo);
            List<SysDictData> statusArray = DictUtils.getDictCache("degreas_document_status");
            Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
            for (PdaDto entity : pdaDtos) {
                entity.setStatusDict(statusMap.get(entity.getStatus()));
            }
            return pdaDtos;
        }else {
            return new ArrayList<>();
        }
    }

    /**
     * 根据关联单号查询水刺投料信息
     *
     * @param materialNumber
     * @return
     */
    @Override
    public List<MaterialResumeDto> selectSpunlaceOrderInfo(String materialNumber) {
        return spunlaceOrderMapper.selectSpunlaceOrderInfo(materialNumber);
    }

    /**
     * 根据关联单号查询水刺制令单信息
     *
     * @param feedOrderNumber
     * @return
     */
    @Override
    public SpunlaceOrder selectDocumentStatusInfo(String feedOrderNumber) {
        return spunlaceOrderMapper.selectOne(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getSpunlaceOrderNumber, feedOrderNumber));
    }

    /**
     * 根据生产计划单号查询水刺制令单数据(生产排程退回调用fegin)
     *
     * @param planNumber
     * @return
     */
    @Override
    public boolean getStatusByPlanNumber(String planNumber) {

        List<SpunlaceOrderDto> sunlaceList = spunlaceOrderMapper.getSunlaceList(planNumber);
        boolean isAll = true;
        for (SpunlaceOrderDto entity : sunlaceList) {
            if (!("8".equals(entity.getDocumentStatus())) && !("9".equals(entity.getDocumentStatus()))) {
                isAll = false;
                break;
            }
        }
        return isAll;
    }

    /**
     * Fegin删除水刺制令单
     * @param planNumber
     * @return
     */
    @Override
    public boolean remove(String planNumber) {
        boolean remove = remove(new QueryWrapper<SpunlaceOrder>().lambda().eq(SpunlaceOrder::getSpunlaceOrderNumber, planNumber));
        if (remove){
            cutOrdersDocumentService.remove(new QueryWrapper<CutOrdersDocument>().lambda().eq(CutOrdersDocument::getSplittingOrderNumber,planNumber));
        }else{
            throw new GlobalException("删除失败");
        }
        return remove;
    }

    /**
     * 水刺和脱脂制令单列表
     * @param
     * @return
     */
    @Override
    public List<ScFqDto> getMoSpunlaceAndDegrease(String productionLine) {
        List<ScFqDto> list = spunlaceOrderMapper.getMoSpunlaceAndDegrease(productionLine);
        return list;
    }
}
